@Data is like having implicit @Getter, @Setter, @ToString, @EqualsAndHashCode and @RequiredArgsConstructor annotations on the class (except that no constructor will be generated if any explicitly written constructor exists).
@RequiredArgsConstructor generates a constructor with 1 parameter for
each field that requires special handling. All non-initialized final
fields get a parameter, as well as any fields that are marked as
@NonNull that aren't initialized where they are declared. For those
fields marked with @NonNull, an explicit null check is also generated.
The constructor will throw a NullPointerException if any of the
parameters intended for the fields marked with @NonNull contain null.
The order of the parameters match the order in which the fields appear
in your class.
假设您有一个使用Lombok@Data注释的POJO:
public @Data class Z {
private String x;
private String y;
}
无法将对象创建为Z z = new Z(x, y);,因为Z类上没有“必需”的参数。它使用零参数创建构造函数,因为@Data为您的属性提供setter和getter,您可以在创建实例后调用setX和setY
# 1 楼答案
如果没有定义构造函数,将生成
@RequiredArgsConstructor
该Project Lombok @Data page说明:
# 2 楼答案
@Data仅在创建@RequiredArgsConstructor。Lombok的Data annotation和constructors文档站点解释:
假设您有一个使用Lombok@Data注释的POJO:
无法将对象创建为
Z z = new Z(x, y);
,因为Z类上没有“必需”的参数。它使用零参数创建构造函数,因为@Data为您的属性提供setter和getter,您可以在创建实例后调用setX和setY您可以将x和y设置为@NonNull或final,以便它们必须通过构造函数传递,或者使用@allargsconstuctor注释类Z